<template>
  <div>
    <el-row style="margin: 10px 0;">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/bashbord' }">首页</el-breadcrumb-item>
        <div v-if="hostId != null">
          <el-breadcrumb-item :to="{ path: '/ecs-list' }">主机管理</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/ecs-detail?hostId=' + this.hostId }">主机概览</el-breadcrumb-item>
          <el-breadcrumb-item>{{tabName}}</el-breadcrumb-item>
        </div>
        <div v-else>
          <el-breadcrumb-item :to="{ path: '/cluster-detail' }">集群管理</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/cluster-detail?tab=slqk' }">实例</el-breadcrumb-item>
          <el-breadcrumb-item>{{tabName}}</el-breadcrumb-item>
        </div>
      </el-breadcrumb>
    </el-row>

    <el-tabs v-model="defaultActivityName" @tab-click="handleClick">
      <el-tab-pane label="概览" name="first">
        <div style="width:95%;margin-bottom:15px;display:flex;flex-direction:row;align-items:center;justify-content:flex-end;">
          <el-select size="small"  style="width:100px;margin-right:10px" v-model="time" clearable placeholder="刷新时间"  @change="changeTime">
            <el-option v-for="item in selectTime" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>

          <el-select size="small"  style="width:130px;" multiple v-model="chart" placeholder="选择图表">
            <el-option v-for="item in selectChart" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </div>

        <div style="width:100%;display:flex;flex-direction:row;justify-content:space-evenly">
          <div style="width:25%;display:flex;flex-direction:column;">
            <el-card v-loading="loading" style="width:95%;margin:10px;">
              <el-row>
                <el-col :span="1"><div style="width: 4px;height: 17px;background-color: #409EFF;"></div></el-col>
                <el-col :span="5" style="line-height: 17px">基本信息</el-col>
              </el-row>
              <el-row class="row">
                <el-col :span="15" class="color">操作</el-col>
                <el-col :span="5">
                  <el-select size="mini"  style="width:100px;" clearable v-model="value" placeholder="操作"  @change="operation">
                    <el-option v-for="(item,index) in select" :key="index" :label="item.label" :value="item.value"></el-option>
                  </el-select>
                </el-col>
              </el-row>
              <el-row class="row">
                <el-col :span="14" class="color">版本号</el-col>
                <el-col :span="10" class="font">{{essentialInformation.version}}</el-col>
              </el-row>
              <el-row class="row">
                <el-col :span="14" class="color">IP地址</el-col>
                <el-col :span="10" class="font">{{essentialInformation.ip}}</el-col>
              </el-row>
              <el-row class="row">
                  <el-col :span="14" class="color">安装地址</el-col>
                  <el-col :span="10" class="font">{{essentialInformation.installationPath}}</el-col>
                </el-row>
              <el-row class="row">
                <el-col :span="14" class="color">内存</el-col>
                <el-col :span="10" class="font">{{essentialInformation.memory}}</el-col>
              </el-row>
              <el-row class="row">
                <el-col :span="14" class="color">CPU</el-col>
                <el-col :span="10" class="font">{{essentialInformation.cpu}}</el-col>
              </el-row>
              <el-row class="row">
                <el-col :span="14" class="color">角色</el-col>
                <el-col :span="10" class="font">{{essentialInformation.role}}</el-col>
              </el-row>
              <el-row class="row">
                <el-col :span="14" class="color">状态</el-col>
                <el-col :span="10" class="font">
                  <div v-if="essentialInformation.state == 'ACTIVE'">
                    <div style="width: 8px;height: 8px;background-color: #5EDD86;border-radius: 50%;display:inline-block"></div>
                    <div style="display:inline-block">{{runStates[0].label}}</div>
                  </div>
                  <div v-else>
                    <div style="width: 8px;height: 8px;background-color: red;border-radius: 50%;display:inline-block"></div>
                    <div style="display:inline-block">{{runStates[2].label}}</div>
                  </div>
                </el-col>
              </el-row>
            </el-card>

            <el-card v-loading="loading" style="width:95%;margin:10px;">
              <el-row>
                <el-col :span="1"><div style="width: 4px;height: 17px;background-color: #409EFF;"></div></el-col>
                <el-col :span="3" style="line-height: 17px;margin-bottom: 5px;">日志</el-col>
              </el-row>
              <el-row v-for="(item,index) in essentialInformation.log" :key="index" style="margin:10px 0;">
                <el-col :span="19" style="color:#409EFF ">{{item}}</el-col>
                <el-col :span="5" style="color:#409EFF;cursor:pointer;"><span @click="downLogFile(item)">下载</span></el-col>
              </el-row>
            </el-card>
          </div>

          <div style="width:75%;display:flex;flex-direction:row;flex-wrap:wrap;">

            <el-card style="width:47.5%;height:367px;margin:10px;" v-show="showCpu" v-loading="loading">
              <el-row>
                <el-col :span="1"><div style="width: 4px;height: 17px;background-color: #409EFF;"></div></el-col>
                <el-col :span="8" style="line-height: 17px">实例CPU使用率</el-col>
              </el-row>
              <el-row>
                <div style="width:100%;height:350px;" id="cpuUtilization"></div>
              </el-row>
            </el-card>

            <el-card style="width:47.5%;height:367px;margin:10px;" v-show="showMemory" v-loading="loading">
              <el-row>
                <el-col :span="1"><div style="width: 4px;height: 17px;background-color: #409EFF;"></div></el-col>
                <el-col :span="5" style="line-height: 17px">实例内存使用率</el-col>
              </el-row>
              <el-row>
                <div  style="width:100%;height:350px;" id="memoryUsage"></div>
              </el-row>
            </el-card>

          </div>
        </div>

        <!-- <div>
          <el-dialog :visible.sync="dialogVisible" append-to-body v-model="dialogVisible" title="提示" width="540px" @closed="closeDelDia">
            <span>确认卸载此实例?</span>
            <template #footer>
              <div class="adv_del">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="del">确认</el-button>
              </div>
            </template>
          </el-dialog>
        </div> -->
      </el-tab-pane>

      <el-tab-pane label="配置" name="second">
        <el-row type="flex" justify="end" v-loading="loading">
          <el-col :span="1"><el-button class="btn" @click="changeClassState('restart')">启动</el-button></el-col>
          <el-col :span="1"><el-button class="btn" @click="changeClassState('stop')">停止</el-button></el-col>
          <!-- <el-col :span="1"><el-button class="btn">升级</el-button></el-col> -->
          <el-col :span="1"><el-button class="btn" @click="remove">卸载</el-button></el-col>
          <el-col :span="1"><el-button class="btn" @click="changeClassState('restart')">重启</el-button></el-col>
        </el-row>
        <el-row>
          <config :showButton="'true'"></config>
        </el-row>
      </el-tab-pane>
        <el-dialog :visible.sync="dialogVisible" v-model="dialogVisible" title="卸载实例" width="540px" @closed="closeDelDia" v-loading="loading">
          <el-checkbox v-model="removeDirectory" label="卸载实例是否同步删除目录？" size="large"></el-checkbox>
          <template #footer>
            <div class="adv_del">
              <el-button @click="dialogVisible = false,value = ''">取消</el-button>
              <el-button type="primary" @click="removeColonyOrNode">确认</el-button>
            </div>
          </template>
        </el-dialog>
    </el-tabs>
  </div>
</template>
<script>
import {doGet, doPost} from '@/api/index.js'
import clusterlist from '@/view/cluster/list'
import * as echarts from 'echarts'
import config from '@/view/config/config'

export default {
  props: {},
  name:'node-detail',
  created(){
    this.clusterId=this.$route.query.clusterId
    this.hostId=this.$route.query.hostId
  },
  components: {
    'clusterlist': clusterlist,
    'config': config
  },
  data () {
    return {
      hostId:'',
      removeDirectory:false,
      dialogVisible:false,
      loading:false,
      tabName:'实例概览',
      diskList:[
        {
          'diskName':'虚拟磁盘',
          'mountPoint':33,
          'diskUsage':20,
          'diskCapacity':'2G/10G'
        }
      ],
      disk:{
        time:[],
        percentage:[]
      },
      memory:{
        time:[],
        percentage:[]
      },
      cpu:{
        time:[],
        percentage:[]
      },
      runStates: [{
        value: 'ACTIVE',
        label: '运行中'
      }, {
        value: 'INACTIVE',
        label: '空闲'
      }, {
        value: 'SHUTTING_DOWN',
        label: '关闭'
      }],
      //basic information and role information
      essentialInformation:{
        'version':'- -',
        'ip':'- -',
        'memory':'- -',
        'cpu':'- -',
        'state':'- -',
        'role':'- -',
        'log':[],
        'ecsId':''
      },
      select: [{
        value: 'start',
        label: '启动'
      },{
        value: 'stop',
        label: '停止'
      },
      // {
      //   value: 'upgrade',
      //   label: '升级'
      // },
      {
        value: 'del',
        label: '卸载'
      },{
        value: 'restart',
        label: '重启'
      }],
      selectTime:[{
        value: '0',
        label: '实时'
      },{
        value: '1',
        label: '1小时'
      },{
        value: '2',
        label: '2小时'
      },{
        value: '3',
        label: '6小时'
      },{
        value: '4',
        label: '12小时'
      },{
        value: '5',
        label: '1天'
      },{
        value: '6',
        label: '1周'
      },{
        value: '7',
        label: '1月'
      }],
      time:'0',
      chart:'',
      value:'',
      selectChart:[{
        value: 'cpu',
        label: '实例CPU使用率'
      },{
        value: 'memory',
        label: '实例内存使用率'
      },],
      title:{
        manageIp:'1',
        serviceIp:'2',
        ram:'3',
        totalRam:'4',
        cpu:'5',
        totalCpu:'6',
        clusterNum:'7',
        totalClusterNum:'8'
      },
      clusterId:'',
      defaultActivityName: 'first',
      CarbonDataName: 'CarbonData',
      currentConfigType: 'ClickHouse',
      activeName: 'second',
      tabPosition: 'left',
      data: {
        'common': {
          'common1': {
            'join-distribution-type': 'AUTOMATIC',
            'redistribute-writes': true
          }
        },
        'jvm': {
          'jvm1': {
            'jvm': '22222222222'
          }
        },
        'ClickHouse': {
          ClickHouseTabsValue: '1',
          clickHouseTabIndex: 2,
          ClickHouseTabs: [
            {
              title: '连接器1',
              name: '1',
              configGroup: '1',
            }
          ],

          'ClickHouse1': {
            'connector.name': 'clickhouse',
            'connection-url': 'jdbc:clickhouse0://example.net:8123',
            'connection-user': 'username',
            'connection-password': 'yourpassword',
            'allow-drop-table': true
          },

          'ClickHouse2': {
            'connector.name': 'clickhouse',
            'connection-url': 'jdbc:clickhouse1://example.net:8123',
            'connection-user': 'username',
            'connection-password': 'yourpassword',
            'allow-drop-table': true
          },

        }

      },
      clock:null,
      clock2:null,
      flag:true,
      memoryEcharts:null,
      cpuEcharts:null,
      cpuResultList:[],
      memoryResultList:[],
    }
  },
  mounted () {
    this.loading = true;
    this.memoryEcharts = echarts.init(document.getElementById('memoryUsage'), null);
    this.cpuEcharts = echarts.init(document.getElementById('cpuUtilization'), null);

    this.clock=setInterval(()=>{
      if(this.flag){
        this.queryNodeItem();
      }
    },1000)

    this.clock2=setInterval(()=>{
      this.getEchartsData();
    },1000)
    this.bgColor();
    this.initCpuUtilization()
    this.initMemoryUsage()
  },
  beforeDestroy()
  {
    clearInterval(this.clock)
    clearInterval(this.clock2)
    this.clock=null
    this.clock2=null
  },
  methods: {
    //open uninstall dialog
    remove(){
      this.dialogVisible=true;
    },
    //uninstall cluster
    removeColonyOrNode(){
      this.loading=true;
      let url='/sys_openlookeng_cluster/removeColonyOrNode';
      let obj={
        'state':'stop',
        'nodeIds':[this.clusterId],
        'removeDirectory':this.removeDirectory
      };
      doPost(url,obj).then(res=>{
        this.dialogVisible=false;
        this.loading=false;
        if (res.data.code == 0){
          this.$message.success(res.data.msg);
          this.$router.push('/cluster-detail?tab=slqk')
        }
      });
    },
    //start,shut down,restart cluster
    changeClassState(state){
      this.loading=true;
      let obj={
        'state':state,
        'nodeIds':[this.clusterId]
      };
      let url='/sys_openlookeng_cluster/changeClassState';
      doPost(url,obj).then(res=>{
        this.loading=false;
        if (res.data.code == 0){
          this.$message.success(res.data.msg);
        }
      });
    },
    downLogFile(val){
      this.loading=true;
      let that=this;
      let url = '/sys_ecs/downloadFile'
      let obj = {
        'ecsId': this.essentialInformation.ecsId,
        'fileName': val
      }
      doPost(url, obj).then(res => {
        that.loading=false;
        this.logFilePathsVal='';
        if (res.data.code == 0){
          let baseApi=`${process.env.UPLOAD_PARAM}` + res.data.data;
          that.downloadRes(val,baseApi)
        }
        else
        {
          this.$message.error("下载失败")
        }
      })
    },
    async downloadRes(name,url){
      let response = await fetch(url); //change content as blob address
      let blob = await response.blob();  //create hidden download link
      let objectUrl = window.URL.createObjectURL(blob);
      let a = document.createElement('a');
      a.href = objectUrl;
      a.download = name;
      a.click()
      a.remove();
    },
    queryNodeItem(){
      let that=this;
      that.flag = false;
      let url="/sys_openlookeng_cluster/v2/queryNodeItem";
      let obj={'id':this.clusterId}
      doGet(url,obj).then(res=>{
        if(res.data.code===0){
          let data = res.data.data;
          this.essentialInformation=data;
          this.essentialInformation.memory=data.useRam + "G/" + data.totalRam + "G";
          this.essentialInformation.cpu=data.useCpu + "Core/" + data.totalCpu + "Core";
          that.loading=false;
          // debugger
        }
        setTimeout(()=>{
          that.flag = true;
        },1000)
      });
    },
    bgColor(){
      document.body.style.backgroundColor="#F9F9F9 ";
    },
    initMemoryUsage(echartData)
    {
      let that=this;
      let option =
      {
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          type: 'category',
          boundaryGap:false,
          axisLabel:
          {
            interval:1,
            formatter:function(value)
            {
              return value.slice(0,11)+"\n"+value.slice(11)
            }
          },
          splitLine: {
            show: false
          }
        },
        yAxis: {
          name:'(单位%)',
          type: 'value',
          max:100
        },
        series: [
          {
            data:echartData,
            type: 'line',
            showSymbol: false,
          }
        ]
      }
      new Promise((resolve)=>{resolve();}).then(()=>
      {
        that.memoryEcharts.setOption(option);
      })
    },
    initCpuUtilization(echartData)
    {
      let that=this;
      let option =
      {
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          type: 'category',
          boundaryGap:false,
          axisLabel:
          {
            interval:1,
            formatter:function(value)
            {
              return value.slice(0,11)+"\n"+value.slice(11)
            }
          },
          splitLine: {
            show: false
          }
        },
        yAxis: {
          name:'(单位%)',
          type: 'value',
          max:100
        },
        series: [
          {
            data:echartData,
            type: 'line',
            showSymbol: false,
          }
        ]
      }
      new Promise((resolve)=>{resolve();}).then(()=>
      {
        that.cpuEcharts.setOption(option);
      })
    },
    getEchartsData()
    {
      this.cpuResultList=[];
      this.memoryResultList=[];
      let that = this;
      let url = "/sys_ecs/clusterEchartInfo";
      let obj =
      {
        'nodeId':this.clusterId,
        queryType:this.time
      }
      doGet(url, obj).then(res =>
      {
        if(res.data.code==0)
        {
          that.initCpuUtilization(that.formatEchartsData(that.cpuResultList,res.data.data.cpuInfoList));
          that.initMemoryUsage(that.formatEchartsData(that.memoryResultList,res.data.data.menInfoList));
        }
      })
    },
    formatEchartsData(list,arr)
      {
        if(list.length==0)
        {
          for(let i=0;i<arr.length;i++)
          {
            list.push([arr[i].time,arr[i].value])
          }
        }
        else
        {
          list.splice(0,1);
          list.push([arr[arr.length-1].time,arr[arr.length-1].value])
        }
        return list
      },
    changeTime(){
      this.cpuResultList=[];
      this.memoryResultList=[];
    },
    closeDelDia(e){},
    del(e){},
    operation(val){
      //start,shut down, upgrade, delete, restart node
      if (val == 'start' || val == 'stop' || val == 'restart'){
        if(val == 'start')
        {
          val='restart'
        }
        this.changeNodeState(val);
      }
      else if (val =='del'){
        this.remove();
      }
      // this.queryNodeItem();
    },
    changeNodeState(state){
      this.loading=true;
      let url=`/sys_openlookeng_cluster/changeNodeState?nodeId=${this.clusterId}&state=${state}`;
      doPost(url).then(res=>{
        this.loading=false;
        this.value='';
        if (res.data.code == 0){
          this.$message.success(res.data.msg);
        }
      });
    },
    getClusterConfig () {
      let apiUrl = '/sys_openlookeng_cluster_config/getClusterConfig'
      let param = {'clusterCode': 'yuelianwgan'}
      let _this = this
      doGet(apiUrl, param).then((response) => {
        //debugger
        _this.data = response.data.data
      })

    },

    handleClick (tab, event) {
      this.currentConfigType = tab.name
      if (tab.name == "second"){
        this.tabName="实例配置";
      }else {
        this.tabName="实例概览";
      }
    },
    handleTabsEdit (targetName, action) {
      let configType = this.currentConfigType
      let tabsArrayName = configType + 'Tabs'
      let tabsValName = configType + 'TabsValue'
      let tabsIndexName = configType + 'TabIndex'
      if (action === 'add') {
        let newTabName = ++this.data[configType][tabsIndexName] + ''
        let configGroup = configType + newTabName
        let obj = {
          title: '连接器' + newTabName,
          name: newTabName,
          configGroup: this.data[configType][tabsIndexName]
        }
        this.data[configType][tabsArrayName].push(obj)
        this.data[configType][tabsValName] = newTabName
        this.data[configType][configGroup] = {}
      }
      if (action === 'remove') {
        let tabs = this.data[configType][tabsArrayName]
        if (tabs.length == 1) {
          this.$message.error('请保留至少一个配置!')
          return false
        }
        let activeName = this.data[configType][tabsValName]
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.name === targetName) {
              let nextTab = tabs[index + 1] || tabs[index - 1]
              if (nextTab) {
                activeName = nextTab.name
              }
            }
          })
        }
        this.data[configType][tabsValName] = activeName
        this.data[configType][tabsArrayName] = tabs.filter(tab => tab.name !== targetName)
      }
    }

  },
  computed:
  {
    showCpu()
    {
      return this.chart.length==0||this.chart.indexOf("cpu")!==-1
    },
    showMemory()
    {
      return this.chart.length==0||this.chart.indexOf("memory")!==-1
    },
  },
}
</script>
<style>
.btn{
  color: #409EFF;
  border-color: #409EFF;
}
.color{
  color: #999999;
}
.row{
  height: 28px;
  margin-top: 5px;
  line-height: 28px;
  font-size: 13px;
}
.font{
  font-size: 13px;
  line-height: 28px;
}
</style>
